<template>
  <div class="user-management-container">
    <div class="management-header">
      <h1>用户管理</h1>
      <p>管理系统中的所有用户</p>
    </div>

    <div class="management-actions">
      <div class="search-box">
        <input
          type="text"
          v-model="searchKeyword"
          placeholder="搜索用户名、邮箱或真实姓名..."
          @input="handleSearch"
        />
        <span class="search-icon">🔍</span>
      </div>
      <div class="action-buttons">
        <button class="btn-refresh" @click="loadUsers" :disabled="loading">
          <span v-if="loading" class="btn-spinner"></span>
          {{ loading ? '刷新中...' : '刷新' }}
        </button>
      </div>
    </div>

    <div class="users-table-container">
      <div class="table-wrapper">
        <table class="users-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>用户名</th>
              <th>邮箱</th>
              <th>真实姓名</th>
              <th>手机号</th>
              <th>注册时间</th>
              <th>更新时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in paginatedUsers" :key="user.userId">
              <td>{{ user.userId }}</td>
              <td>
                <div class="user-info">
                  <div class="user-avatar">
                    {{ user.username.charAt(0).toUpperCase() }}
                  </div>
                  <div>
                    <div class="username">{{ user.username }}</div>
                    <div class="user-role" v-if="user.username === 'admin'">管理员</div>
                  </div>
                </div>
              </td>
              <td>{{ user.email || '-' }}</td>
              <td>{{ user.realName || '-' }}</td>
              <td>{{ user.phone || '-' }}</td>
              <td>{{ formatDate(user.createdAt) }}</td>
              <td>{{ formatDate(user.updatedAt) }}</td>
              <td class="actions">
                <button 
                  class="btn-edit"
                  @click="editUser(user.userId!)"
                  title="编辑用户"
                >
                  编辑
                </button>
                <button 
                  class="btn-delete"
                  @click="confirmDelete(user)"
                  :disabled="user.username === 'admin'"
                  :title="user.username === 'admin' ? '不能删除管理员' : '删除用户'"
                >
                  删除
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载用户数据中...</p>
      </div>

      <div v-if="!loading && filteredUsers.length === 0" class="empty-state">
        <div class="empty-icon">📝</div>
        <h3>没有用户数据</h3>
        <p>当前没有找到匹配的用户记录</p>
      </div>

      <!-- 分页控件 -->
      <div v-if="filteredUsers.length > 0" class="pagination">
        <button 
          class="pagination-btn"
          :disabled="currentPage === 1"
          @click="currentPage--"
        >
          上一页
        </button>
        <span class="pagination-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </span>
        <button 
          class="pagination-btn"
          :disabled="currentPage === totalPages"
          @click="currentPage++"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div v-if="showDeleteConfirm" class="modal-overlay" @click="showDeleteConfirm = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
        </div>
        <div class="modal-body">
          <p>确定要删除用户 <strong>"{{ userToDelete?.username }}"</strong> 吗？</p>
          <p class="warning-text">此操作不可恢复，请谨慎操作！</p>
        </div>
        <div class="modal-actions">
          <button class="btn-cancel" @click="showDeleteConfirm = false">取消</button>
          <button class="btn-confirm" @click="deleteUser" :disabled="deleting">
            <span v-if="deleting" class="btn-spinner"></span>
            {{ deleting ? '删除中...' : '确认删除' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import type { User } from '@/api/user'

const router = useRouter()
const userStore = useUserStore()

const users = ref<User[]>([])
const searchKeyword = ref('')
const loading = ref(false)
const deleting = ref(false)
const showDeleteConfirm = ref(false)
const userToDelete = ref<User | null>(null)
const currentPage = ref(1)
const pageSize = 10

// 计算属性
const filteredUsers = computed(() => {
  if (!searchKeyword.value.trim()) {
    return users.value
  }
  
  const keyword = searchKeyword.value.toLowerCase().trim()
  return users.value.filter(user => 
    user.username.toLowerCase().includes(keyword) ||
    (user.email && user.email.toLowerCase().includes(keyword)) ||
    (user.realName && user.realName.toLowerCase().includes(keyword)) ||
    (user.phone && user.phone.includes(keyword))
  )
})

const totalPages = computed(() => {
  return Math.ceil(filteredUsers.value.length / pageSize)
})

const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return filteredUsers.value.slice(start, end)
})

// 方法
const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  try {
    return new Date(dateString).toLocaleDateString('zh-CN')
  } catch (e) {
    return '-'
  }
}

const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置到第一页
}

const editUser = (userId: number) => {
  router.push(`/admin/users/edit/${userId}`)
}

const confirmDelete = (user: User) => {
  if (user.username === 'admin') {
    ElMessage.warning('不能删除管理员账户')
    return
  }
  userToDelete.value = user
  showDeleteConfirm.value = true
}

const deleteUser = async () => {
  if (!userToDelete.value?.username) return
  
  deleting.value = true
  try {
    const result = await userStore.deleteUserById(userToDelete.value.username)
    if (result.operateResult === 'SUCCESS') {
      // 从列表中移除已删除的用户
      users.value = users.value.filter(u => u.username !== userToDelete.value!.username)
      showDeleteConfirm.value = false
      userToDelete.value = null
      ElMessage.success('用户删除成功')
    } else {
      ElMessage.error(result.errorMsg || '删除失败')
    }
  } catch (error) {
    ElMessage.error('删除失败，请稍后重试')
  } finally {
    deleting.value = false
  }
}

const loadUsers = async () => {
  loading.value = true
  try {
    const response = await userStore.fetchAllUsers()
    if (response.operateResult === 'SUCCESS' && response.data) {
      users.value = response.data
    } else {
      ElMessage.error(response.errorMsg || '获取用户列表失败')
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-management-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.management-header {
  text-align: center;
  margin-bottom: 40px;
}

.management-header h1 {
  font-size: 32px;
  color: #1e293b;
  margin-bottom: 8px;
  font-weight: 600;
}

.management-header p {
  color: #64748b;
  font-size: 16px;
}

.management-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  gap: 16px;
}

.search-box {
  position: relative;
  flex: 1;
  max-width: 400px;
}

.search-box input {
  width: 100%;
  padding: 12px 16px 12px 40px;
  border: 2px solid #e5e7eb;
  border-radius: 10px;
  font-size: 14px;
  transition: all 0.2s;
}

.search-box input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #6b7280;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.btn-refresh {
  background: #3b82f6;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: background-color 0.2s;
}

.btn-refresh:hover:not(:disabled) {
  background: #2563eb;
}

.btn-refresh:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.users-table-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  border: 1px solid #e2e8f0;
}

.table-wrapper {
  overflow-x: auto;
}

.users-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 800px;
}

.users-table th {
  background: #f8fafc;
  padding: 16px 12px;
  text-align: left;
  font-weight: 600;
  color: #374151;
  border-bottom: 1px solid #e5e7eb;
  font-size: 14px;
}

.users-table td {
  padding: 16px 12px;
  border-bottom: 1px solid #f1f5f9;
  color: #64748b;
}

.users-table tbody tr:hover {
  background: #f9fafb;
}

.users-table tbody tr:last-child td {
  border-bottom: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 14px;
}

.username {
  font-weight: 500;
  color: #1e293b;
}

.user-role {
  font-size: 12px;
  color: #6b7280;
  background: #f1f5f9;
  padding: 2px 8px;
  border-radius: 12px;
  display: inline-block;
  margin-top: 2px;
}

.actions {
  display: flex;
  gap: 8px;
}

.btn-edit {
  background: #3b82f6;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: background-color 0.2s;
}

.btn-edit:hover {
  background: #2563eb;
}

.btn-delete {
  background: #ef4444;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: background-color 0.2s;
}

.btn-delete:hover:not(:disabled) {
  background: #dc2626;
}

.btn-delete:disabled {
  background: #9ca3af;
  cursor: not-allowed;
  opacity: 0.5;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f1f5f9;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

.loading-state p {
  color: #64748b;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state h3 {
  color: #1e293b;
  margin-bottom: 8px;
}

.empty-state p {
  color: #64748b;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  border-top: 1px solid #e5e7eb;
  gap: 16px;
}

.pagination-btn {
  background: white;
  border: 1px solid #d1d5db;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.pagination-btn:hover:not(:disabled) {
  background: #f9fafb;
  border-color: #9ca3af;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-info {
  color: #6b7280;
  font-size: 14px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
  max-width: 400px;
  width: 90%;
  overflow: hidden;
}

.modal-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  color: #1e293b;
  margin: 0;
}

.modal-body {
  padding: 24px;
}

.modal-body p {
  margin-bottom: 8px;
  color: #64748b;
}

.warning-text {
  color: #ef4444 !important;
  font-weight: 500;
}

.modal-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding: 20px 24px;
  border-top: 1px solid #e5e7eb;
}

.btn-cancel {
  background: #6b7280;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
}

.btn-cancel:hover {
  background: #4b5563;
}

.btn-confirm {
  background: #ef4444;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-confirm:hover:not(:disabled) {
  background: #dc2626;
}

.btn-confirm:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .management-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    max-width: none;
  }
  
  .action-buttons {
    justify-content: flex-end;
  }
  
  .pagination {
    flex-direction: column;
    gap: 12px;
  }
  
  .modal-actions {
    flex-direction: column;
  }
}
</style>